import { PrismaClient } from '@prisma/client';
import { PrismaService } from 'nestjs-prisma';
import { QueryPageDto } from '../dto/query.page.dto';
import { GetSkit, GetSort } from '../utils/query';
import { PageDto } from '../dto/page.dto';

export class BaseService {
  constructor(
    protected readonly prisma: PrismaService,
    protected readonly model: keyof PrismaClient,
  ) {}

  private get repo() {
    return this.prisma[this.model] as any;
  }

  async findByPage(query: any, where: any = {}) {
    const skip = GetSkit(query);
    const order = GetSort(query);

    const [items, total] = await Promise.all([
      this.repo.findMany({ ...skip, ...order, where }),
      this.repo.count({ where }),
    ]);

    return new PageDto(query, items, total);
  }
  findAll(where: any = {}) {
    return this.repo.findMany({ where });
  }

  async findOne(id: string) {
    return this.repo.findUnique({ where: { id } });
  }

  async create(data: any) {
    return this.repo.create({ data });
  }

  async update(id: string, data: any) {
    return this.repo.update({ where: { id }, data });
  }

  async remove(id: string) {
    return this.repo.delete({ where: { id } });
  }
}
